package com.lyandwc.lw_bbs.security.common;

import com.lyandwc.lw_bbs.security.entity.Auth;
import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import com.lyandwc.lw_bbs.security.service.AuthService;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class UserPermEvaluator implements PermissionEvaluator {
    private AuthService authService;

    public UserPermEvaluator(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        UserAuthDetails userAuthDetails = (UserAuthDetails) authentication.getPrincipal();

        Set<String> permissions = new HashSet<>();

        List<Auth> authList = authService.findAuthByUserId(userAuthDetails.getId());
        authList.forEach(auth -> permissions.add(auth.getPermission()));

        return permissions.contains(permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
